﻿using FluentValidation;
using FluentValidation.Results;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Data.DbUtils;
using PMS.Data.Entities.SystemModules;
using PMS.Web.Framework.Validators;
using PMS.Web.Models.SystemModules;
using System;

namespace PMS.Web.Validators.Customer
{
    public partial class SystemModuleModelValidator : BaseModelValidator<SystemModuleModel>
    {
        public SystemModuleModelValidator(IDbContext dbContext)
        {
            RuleFor(m => m.Name).NotEmpty().WithMessage(string.Format(ValidatorRuleString.FieldRequired, "名称"));
            RuleFor(m => m.RouteUrl).NotEmpty().When(m => m.OpenMode != LinkOpenMode.None).WithMessage(ValidatorRuleString.RouteUrlRequiredWhenSystemModule);
            RuleFor(m => m.ModuleAssignedButtonIds).Must(x => x?.Count == 0).When(m => m.OpenMode == LinkOpenMode.None).WithMessage(ValidatorRuleString.ModuleButtonsEmptyWhenNaviMenu);
            RuleFor(m => m.LimitedStoreIds).Must(x => x?.Count == 0).When(m => m.OpenMode == LinkOpenMode.None).WithMessage(ValidatorRuleString.LimitedStoresEmptyWhenNaviMenu);
            SetDatabaseValidationRules<SystemModule>(dbContext);
        }

        protected override bool PreValidate(ValidationContext<SystemModuleModel> context, ValidationResult result)
        {
            var httpContextAccessor = context.GetServiceProvider().GetService(typeof(IActionContextAccessor));
            var actionDescriptor = ((IActionContextAccessor)httpContextAccessor).ActionContext.ActionDescriptor as ControllerActionDescriptor;
            var actionName = actionDescriptor?.ActionName;
            var controllerName = actionDescriptor?.ControllerName;
            //https://docs.fluentvalidation.net/en/latest/advanced.html 
            if (controllerName.Equals("SystemModuleWebApi", StringComparison.CurrentCultureIgnoreCase) && actionName.Equals("UpdateSystemModuleAuthorizeApi", StringComparison.CurrentCultureIgnoreCase))
                return false;
            return true;
        }
    }
}
